package com.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.config.Constant;
import com.config.URLConstant;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiCspaceAddRequest;
import com.dingtalk.api.request.OapiProcessinstanceCreateRequest;
import com.dingtalk.api.request.OapiProcessinstanceCspaceInfoRequest;
import com.dingtalk.api.request.OapiProcessinstanceGetRequest;
import com.dingtalk.api.response.OapiCspaceAddResponse;
import com.dingtalk.api.response.OapiProcessinstanceCreateResponse;
import com.dingtalk.api.response.OapiProcessinstanceCspaceInfoResponse;
import com.dingtalk.api.response.OapiProcessinstanceGetResponse;
import com.model.ProcessInstanceInputVO;
import com.taobao.api.ApiException;
import com.util.AccessTokenUtil;
import com.util.LogFormatter;
import com.util.LogFormatter.LogEvent;
import com.util.ServiceResult;
import com.util.ServiceResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

/**
 * 企业 E应用审批解决方案示例代码
 * 实现了审批的基础功能
 */
@RestController
public class ProcessinstanceController {
    private static final Logger bizLogger = LoggerFactory.getLogger(ProcessinstanceController.class);

    /**
     * 欢迎页面
     */
    @RequestMapping(value = "/Processinstance/welcome", method = RequestMethod.GET)
    public String welcome() {
        return "welcome";
    }


    /**
     * @param
     * @return java.lang.String
     * @description 获取accessToken
     * @author swain
     * @date 2020/11/27
     */
    @RequestMapping(value = "/getaccesstoken", method = RequestMethod.POST)
    @ResponseBody
    public ServiceResult<String> getAccessToken() {
        try {
            String token = AccessTokenUtil.getToken();
            return ServiceResult.success(token);
        } catch (Exception e) {
            bizLogger.error("获取失败", e);
            return ServiceResult.failure(ServiceResultCode.SYS_ERROR);
        }
    }


    /**
     * 发起审批
     */
    @RequestMapping(value = "/processinstance/start", method = RequestMethod.POST)
    @ResponseBody
    public ServiceResult<String> startProcessInstance(@RequestBody ProcessInstanceInputVO processInstance) {
        try {
            DefaultDingTalkClient client = new DefaultDingTalkClient(URLConstant.URL_PROCESSINSTANCE_START);
            OapiProcessinstanceCreateRequest request = new OapiProcessinstanceCreateRequest();
            request.setProcessCode(Constant.PROCESS_CODE);

            request.setFormComponentValues(processInstance.generateForms());

            /**
             * 如果想复用审批固定流程，使用或签会签的话，可以不传审批人，具体请参考文档： https://open-doc.dingtalk.com/microapp/serverapi2/ebkwx8
             * 本次quickstart，演示不传审批人的场景
             */
            request.setApprovers(processInstance.getOriginatorUserId());
            request.setOriginatorUserId(processInstance.getOriginatorUserId());
            request.setDeptId(processInstance.getDeptId());
            request.setCcList(processInstance.getOriginatorUserId());
            request.setCcPosition("FINISH");

            OapiProcessinstanceCreateResponse response = client.execute(request, AccessTokenUtil.getToken());

            if (response.getErrcode().longValue() != 0) {
                return ServiceResult.failure(String.valueOf(response.getErrorCode()), response.getErrmsg());
            }
            return ServiceResult.success(response.getProcessInstanceId());

        } catch (Exception e) {
            String errLog = LogFormatter.getKVLogData(LogEvent.END,
                    LogFormatter.KeyValue.getNew("processInstance", JSON.toJSONString(processInstance)));
            bizLogger.info(errLog, e);
            return ServiceResult.failure(ServiceResultCode.SYS_ERROR);
        }
    }

    /**
     * 根据审批实例id获取审批详情
     *
     * @param instanceId
     * @return
     */
    @RequestMapping(value = "/pricessinstance/get", method = RequestMethod.POST)
    @ResponseBody
    public ServiceResult getProcessinstanceById(@RequestParam String instanceId) {
        try {
            DingTalkClient client = new DefaultDingTalkClient(URLConstant.URL_PROCESSINSTANCE_GET);
            OapiProcessinstanceGetRequest request = new OapiProcessinstanceGetRequest();
            request.setProcessInstanceId(instanceId);
            OapiProcessinstanceGetResponse response = client.execute(request, AccessTokenUtil.getToken());
            if (response.getErrcode().longValue() != 0) {
                return ServiceResult.failure(String.valueOf(response.getErrorCode()), response.getErrmsg());
            }
            return ServiceResult.success(response.getProcessInstance());
        } catch (Exception e) {
            String errLog = LogFormatter.getKVLogData(LogEvent.END,
                    LogFormatter.KeyValue.getNew("instanceId", instanceId));
            bizLogger.info(errLog, e);
            return ServiceResult.failure(ServiceResultCode.SYS_ERROR);
        }
    }


    /**
     * @param
     * @return java.lang.String
     * @description 获取审批钉盘信息接口
     * @author swain
     * @date 2020/11/27
     */
    public static void getSpaceId() {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/cspace/info");
            OapiProcessinstanceCspaceInfoRequest req = new OapiProcessinstanceCspaceInfoRequest();
            req.setUserId(Constant.USER_ID);
            req.setAgentId(Constant.AGENTID);
            OapiProcessinstanceCspaceInfoResponse rsp = client.execute(req, AccessTokenUtil.getToken());
            System.out.println(rsp.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param
     * @return java.lang.String
     * @description 新增文件到用户自定义空间
     * @author swain
     * @date 2020/11/27
     */
    public static void addSpace() {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/cspace/add");
            OapiCspaceAddRequest req = new OapiCspaceAddRequest();
            req.setAgentId(String.valueOf(Constant.AGENTID));
            req.setCode("d56d81e69xxxxx");
            req.setMediaId("$iAEKAqNxxxx");
            req.setSpaceId("4226670592");
            req.setName("iAEKAqNxxxx.jpg");
            req.setOverwrite(true);
            req.setHttpMethod("GET");
            OapiCspaceAddResponse rsp = client.execute(req, AccessTokenUtil.getToken());
            System.out.println(rsp.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        String s = "{\"processInstanceId\":\"ac3accb8-6e45-4012-8577-11afcefe1d82\",\"finishTime\":1607673095000,\"corpId\":\"ding34a5755559fd902aee0f45d8e4f7c288\",\"EventType\":\"bpms_instance_change\",\"businessId\":\"202012111543000245448\",\"title\":\"曾佳伦提交的提分奖励\",\"type\":\"finish\",\"url\":\"https://aflow.dingtalk.com/dingtalk/mobile/homepage.htm?corpid=ding34a5755559fd902aee0f45d8e4f7c288&dd_share=false&showmenu=false&dd_progress=false&back=native&procInstId=ac3accb8-6e45-4012-8577-11afcefe1d82&taskId=&swfrom=isv&dinghash=approval&dtaction=os&dd_from=corp#approval\",\"result\":\"agree\",\"createTime\":1607672604000,\"processCode\":\"PROC-7C1ADDA7-1B89-499A-85E8-2D799C9541D5\",\"bizCategoryId\":\"\",\"staffId\":\"manager7462\"}";
        JSONObject jsonObject = JSONObject.parseObject(s);

    }

}


